import config from "../config"
import axios from "../core/axios"

//加密存储用户密码
function md5(code){
    code=encodeURI(code)
    var password =String.fromCharCode(code.charCodeAt(0)+code.length)
    for(var i=1;i<code.length;i++){
        password+=String.fromCharCode(code.charCodeAt(i)+code.charCodeAt(i-1))
    }
    return password
}

//读取缓存
function getStorage(key,type=1){
    var res=JSON.parse(localStorage.getItem(md5(key)))
    // if(type == 2){
    //     if(new Date().getTime()>=res.endTime){
    //         res=''
    //     }
    // }
    return res
}

//设置缓存
function setStorage(key,data){
    localStorage.setItem(md5(key),JSON.stringify(data))
}

//拿到当前最新时间
function changeTime(t){
	if(!t){
		t=new Date().getTime()
	}
	let res={}
	res.year=new Date(t).getFullYear()
	res.month=new Date(t).getMonth()+1
	res.month=res.month>9?res.month:'0'+res.month
	res.day=new Date(t).getDate()
	res.day=res.day>9?res.day:'0'+res.day
	res.date=res.year+'-'+res.month+'-'+res.day
	return res.date
}

//上传图片
function uploadImg(file){
    console.log('file',file)
    let type = file.type;
    // file.size 单位是b  1024b = 1kb
    let size = file.size / 1024;
    let link = config.baseApi + '/upload';
    let typelist = 'image/jpeg, image/png, image/jpg, image/gif'
    return new Promise((resolve,reject)=>{
        if(typelist.indexOf(type) === -1){
            resolve({
                code:250,
                msg:'上传的图片格式不正确！'
            })
            return
        }
        if(size > 500){
            console.log(size)
            resolve({
                code:250,
                msg:'图片不能大于500kb!'
            })
            return
        }
        let form = new FormData();
        form.append('file',file);
        axios({
            url:link,
            method:'post',
            data:form,
            headers:{},
            mock:false
        }).then(res => {
            console.log('upload',res)
            resolve(res)
        }).catch(err => {
            reject(err)
        })
        // axios.post(link,form, {
		// 	headers: {}
		// }).then(res => {
		// 	resolve(res.data)
		// }).catch(err => {
		// 	reject(err)
		// })
    })
}

export default {
    getStorage,
    setStorage,
    changeTime,
    uploadImg
}